package com.example.test.util;

//import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.extractor.POITextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
//import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @Author 林文峰
 * @Date 2020/6/19 0019 18:45
 */
public class WordRead {
	
	public static String readWord(MultipartFile file){
		File f = MultipartToFileDemo.toFile(file);
		String text = null;
		try {
			if (f.getAbsolutePath().endsWith(".doc")){
				InputStream ins = new FileInputStream(f);
				WordExtractor wordExtractor = new WordExtractor(ins);
				text = wordExtractor.getText();
				System.out.println(text);
				ins.close();
			}else if (f.getAbsolutePath().endsWith(".docx")){
				OPCPackage opcPackage = POIXMLDocument.openPackage(f.getAbsolutePath());
				POITextExtractor extractor = new XWPFWordExtractor(opcPackage);
				text = extractor.getText();
				System.out.println(text);
				extractor.close();
			}else {
				System.out.println("这不是word文件");
				return "怎么会进入这里面";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		MultipartFileToFile.deleteTempFile(f);
		return text;
	}
}
